package dao.daoimpl;

import util.DataBase;
import dao.CategoryDao;
import bean.Category;
import bean.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class CategoryDaoImpl implements CategoryDao {
    @Override
    public boolean addCategory(Category category) {
        String name=category.getName();
        String time=category.getTime();
        String user=category.getUser();
        String intro=category.getIntro();
        String sql="insert into category_table (category_name,category_time,category_user,category_introduction) values " +
                "('"+name+"','"+time+"','"+user+"','"+intro+"')";
        DataBase.init();
        int flag=DataBase.operate(sql);
        DataBase.release();
        if(flag>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateCategory(Category category) {
        String sql="update category_table set category_name='"+category.getName()+"',category_introduction='"+category.getIntro()+"'where category_id='"+category.getId()+"'";
        DataBase.init();
        int flag=DataBase.operate(sql);
        DataBase.release();
        if(flag>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteCategory(int id) {
        String sql="delete from category_table where category_id='"+id+"'";
        DataBase.init();
        int flag=DataBase.operate(sql);
        DataBase.release();
        if(flag>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean getCategory() {
        return false;
    }

    @Override
    public ArrayList<Category> getCategories(User user) throws SQLException {
        ArrayList<Category> categories=new ArrayList<>();
        String sql="select * from category_table where category_user ='"+user.getAccount()+"'";
        DataBase.init();
        ResultSet resultSet=DataBase.inquire(sql);
        while (resultSet.next()){
            int categoryId=resultSet.getInt("category_id");
            String intro=resultSet.getString("category_introduction");
            String name=resultSet.getString("category_name");
            String time=resultSet.getString("category_time");
            categories.add(new Category(categoryId,name,time,user.getAccount(),intro));
        }
        return categories;
    }
}
